import { cloneDeep } from 'lodash-es'

// 处理文件夹的树形结构
export const folderListToTree = data => {
  const parents = data.filter(function (item: any) {
    return item.folder_id === 0
  })
  const children = data.filter(function (item: any) {
    return item.folder_id !== 0
  })
  // 递归处理层级
  convert(parents, children, 1)
  return parents
}

// 递归处理层级
const convert = (parents: any, children: any, level: number) => {
  parents.forEach(function (item: any) {
    item.level = level + 1
    item.isFolder = true
    item.children = []
    children.forEach(function (current: any, index: any) {
      if (current.folder_id === item.id) {
        const temp = children.filter(function (_v: any, idx: any) {
          return idx !== index
        }) // 删除已匹配项
        item.children.push(current)
        convert([current], temp, item.level) // 递归
      }
    })
  })
}

// 合并当前文件夹下的文件夹和资源
export const mergeFolderSourceData = (folder, source, id, checked, multiple) => {
  const result: any = []
  const getCurrentFolderList = data => {
    data.forEach(item => {
      if (item.folder_id === id) {
        item.isFolder = true
        item.isTitleEdit = false
        item.active = false
        item.children = []
        result.push(item)
      } else {
        if (item.children.length > 0) {
          getCurrentFolderList(item.children)
        }
      }
    })
  }
  getCurrentFolderList(folder)
  if (source.length > 0) {
    let sourceLen = 0
    source.forEach(item => {
      item.isFolder = false
      item.isTitleEdit = false
      item.active = false
      item.imagewidth = parseInt(item.imagewidth)
      item.imageheight = parseInt(item.imageheight)
      item.filesize = parseInt(item.filesize)
      item.fileSize = ''
      if (item.filesize > 0) {
        if (item.filesize / 1024 / 1024 > 1) {
          item.fileSize = Math.floor((item.filesize / 1024 / 1024) * 100) / 100 + 'MB'
        } else {
          item.fileSize = Math.floor((item.filesize / 1024) * 100) / 100 + 'KB'
        }
      } else {
        item.fileSize = '0KB'
      }
      item.fileType = item.mimetype !== '' ? item.mimetype.split('/')[0] : ''

      // 弹窗中上传的内容，默认选中
      if (checked.length > 0) {
        const resUrl = item.url !== '' ? item.url.split('?')[0] : ''
        if (resUrl && checked.indexOf(resUrl) > -1) {
          if (multiple) {
            item.active = true
          } else {
            if (sourceLen === 0) {
              sourceLen += 1
              item.active = true
            } else {
              item.active = false
            }
          }
        }
      }

      result.push(item)
    })
  }
  return result
}

// 树结构数据添加线条结构
export const treeData = (data, isLast, hideLine) => {
  data.forEach((item, index) => {
    if (index === 0) {
      item.isFirst = true
    } else {
      item.isFirst = false
    }
    if (index === data.length - 1) {
      item.isLast = true
    } else {
      item.isLast = false
    }
    item.hideLine = cloneDeep(hideLine)
    if (isLast) {
      item.hideLine.push(item.level - 1)
    }
    if (item.children && item.children.length > 0) {
      treeData(item.children, item.isLast, item.hideLine)
    }
  })
}

// 通过当前选中节点找其所有祖先层级
export const getTreeNodeParents = (list, node) => {
  let arrRes: any = []
  const rev = (data, v) => {
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      if (item.id === v.folder_id) {
        arrRes.unshift(item)
        rev(list, item)
        break
      } else {
        if (item.children.length > 0) {
          rev(item.children, v)
        }
      }
    }
    return arrRes
  }
  arrRes = rev(list, node)
  return arrRes
}

// 通过当前选中节点找其所有祖先层级
export const getTreeExpandNodeParents = (list, id) => {
  let arrRes: any = []
  const rev = (data, v) => {
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      if (item.id === v) {
        arrRes.unshift(item.id)
        rev(list, item.folder_id)
        break
      } else {
        if (item.children.length > 0) {
          rev(item.children, v)
        }
      }
    }
    return arrRes
  }
  arrRes = rev(list, id)
  return arrRes
}

// 获取树结构数据中的指定数据
export const getActiveData = (data, v) => {
  let res = null
  const revert = (arr, id) => {
    arr.forEach((item: any) => {
      if (item.id === id) {
        res = item
      }
      if (item.children.length > 0) {
        revert(item.children, id)
      }
    })
  }
  revert(data, v)
  return res
}

// 返回转化后的数据
export const returnSize = filesize => {
  const fileSize = parseInt(filesize)
  let res = ''
  if (fileSize > 0) {
    if (fileSize / 1024 > 1) {
      res = Math.floor((fileSize / 1024) * 100) / 100 + 'MB'
    } else {
      res = fileSize + 'KB'
    }
  } else {
    res = '0KB'
  }
  return res
}

// 上传时filesize转换
export const returnFileSize = filesize => {
  const fileSize = parseInt(filesize)
  let res = ''
  if (fileSize > 0) {
    if (fileSize / 1024 / 1000 > 1) {
      res = Math.floor((fileSize / 1024 / 1000) * 100) / 100 + 'MB'
    } else {
      res = Math.floor(fileSize / 1000) + 'KB'
    }
  } else {
    res = '0KB'
  }
  return res
}

export const checkSize = async (file, isVideo) => {
  if (!file) return false
  const checktimevideo = document.getElementById('checktimevideo')
  if (checktimevideo) {
    document.body.removeChild(checktimevideo)
  }
  let doms
  if (isVideo) {
    doms = document.createElement('video')
  } else {
    doms = document.createElement('audio')
  }
  const url = URL.createObjectURL(file)
  doms.src = url
  doms.id = 'checktimevideo'
  doms.style.display = 'none'
  document.body.appendChild(doms)
  return await gettime(doms, isVideo)
}

const gettime = (doms, isVideo) => {
  // 由于loadedmetadata 是异步代码所以需要promise进行封装转换为同步代码执行
  const promise = new Promise(resolve => {
    doms.addEventListener('loadedmetadata', e => {
      console.log(doms, 'dom对象')
      console.log(e, '对象')
      const obj = {
        type: '',
        width: 0,
        height: 0,
        duration: 0, // 时长 1表示一秒
        ccbl: [] as any
      }
      if (isVideo) {
        const gcd = getGcd(e.target.videoWidth, e.target.videoHeight)
        obj.type = 'video'
        obj.width = doms.videoWidth
        obj.height = doms.videoHeight
        obj.duration = e.target.duration
        obj.ccbl = [e.target.videoWidth / gcd, e.target.videoHeight / gcd]
      } else {
        obj.type = 'audio'
        obj.duration = e.target.duration
      }
      resolve(obj)
    })
  })
  return promise
}

// 计算最大公约数（尺寸比例）
export const getGcd = (a, b) => {
  let n1, n2
  if (a > b) {
    n1 = a
    n2 = b
  } else {
    n1 = b
    n2 = a
  }
  const remainder = n1 % n2
  if (remainder === 0) {
    return n2
  } else {
    return getGcd(n2, remainder)
  }
}
